package com.kirk.cts.ui.view.panel;

import com.kirk.cts.core.constants.SystemConstants;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p> ViewImagePanel.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-09-01 22:07
 * @Description 显示图片
 */
@Component("viewImagePanel")
@Scope("prototype")
public class ViewImagePanel extends JPanel implements Runnable {
    private static final long serialVersionUID = 1L;

    private JPanel containerPanel;

    // 图标资源缓存
    private Map<String, ImageIcon> imagesCache;

    private String currImagePath;

    public ViewImagePanel() {
        super();
        init();
    }

    private void init() {
        BorderLayout layout = new BorderLayout();
        // 设置布局
        this.setLayout(layout);
        containerPanel = new JPanel();
        // 添加滚动条
        JScrollPane topScrollPane = new JScrollPane(containerPanel);
        this.add(topScrollPane, BorderLayout.CENTER);
        imagesCache = new ConcurrentHashMap<String, ImageIcon>();
    }

    /**
     * 显示图片
     */
    public void showImage(String imagePath) {
        this.currImagePath = imagePath;
    }

    private void initImagesCache() {
        try {
            containerPanel.removeAll();
            if (!getImagesCache().containsKey(this.currImagePath)) {
                ImageIcon image = null;
                if (this.currImagePath.startsWith(SystemConstants.HTTP) || this.currImagePath.startsWith(SystemConstants.HTTPS)) {
                    // 网络图片
                    image = new ImageIcon(new URL(this.currImagePath));
                } else {
                    image = new ImageIcon(this.currImagePath);
                }
                getImagesCache().put(this.currImagePath, image);
            }
            final String path = this.currImagePath;
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    containerPanel.add(new JLabel(getImagesCache().get(path)));
                    containerPanel.repaint();
                    containerPanel.doLayout();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public Map<String, ImageIcon> getImagesCache() {
        return imagesCache;
    }

    public void setImagesCache(Map<String, ImageIcon> imagesCache) {
        this.imagesCache = imagesCache;
    }


    @Override
    public void run() {
        initImagesCache();
    }


}
